import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from game_stats import GameStats

def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height)
    )
    pygame.display.set_caption("Alien Invasion")       # 设置窗口标题为"Alien Invasion"

    ai_settings.load_backgrounds()

    # 创建一艘飞船
    ship = Ship(ai_settings,screen)
    # 创建一个用于储存子弹的编组
    bullets = Group()
    # 创建一个外星人编组
    aliens = pygame.sprite.Group()
    # 创建一个敌军子弹群组
    enemy_bullets = Group()

    # 创建外星人群
    gf.create_mixed_fleet(ai_settings, screen, aliens)
    # 初始化粒子组d
    particles = Group()

    # 计算帧时间a
    clock = pygame.time.Clock()

    # 创建一个用于存储游戏统计信息的实例
    stats = GameStats(ai_settings)

    # 开始游戏的主循环
    while True:
        current_time = pygame.time.get_ticks()

        # 绘制背景
        delta_time = clock.tick(60) / 1000.0    # 转换为秒，例如0.016(60FPS时)
        gf.update_background(ai_settings, delta_time)
        gf.draw_background(ai_settings, screen)

        # 1. 按键指令处理
        gf.check_events(ai_settings, screen, ship, bullets)
        # 2. 更新游戏状态
        ship.update()
        aliens.update()
        if ship.ship_fire:
            gf.fire_bullet(ai_settings, screen, ship, bullets)
        bullets.update()

        # 3，碰撞测试
        gf.update_bullets(bullets)
        # 4. 更新外星人
        gf.update_aliens(ai_settings, ship, aliens, enemy_bullets, particles)
        # 更新粒子
        particles.update()
        # 6.子弹击中外星人
        gf.check_bullet_alien_collisions(ai_settings, screen, aliens, bullets, particles)
        # 敌军子弹发射
        gf.fire_enemy_bullets(aliens, enemy_bullets, current_time, ship)
        gf.update_bullet_positions(enemy_bullets, ai_settings)

        # 每次循环时都重绘屏幕且让绘制的屏幕可见
        gf.update_screen(ai_settings, screen, ship, bullets, aliens, particles, enemy_bullets)
run_game()